# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
import werkzeug

from odoo import http, _
from odoo.addons.auth_signup.controllers.main import AuthSignupHome
from odoo.addons.auth_signup.models.res_users import SignupError
from odoo.exceptions import UserError
from odoo.http import request

_logger = logging.getLogger(__name__)


class AuthSignupHome2(AuthSignupHome):
    @http.route('/web2/signup', type='json', auth='none', cors='*', csrf=False)
    def web_auth_signup2(self, *args, **kw):
        db = request.params.get('db')
        if not db:
            raise UserError(_("没有 db"))

        request.session.db = db

        qcontext = self.get_auth_signup_qcontext()
        # print('xxxxx,web_auth_signup2, 1', qcontext)

        if not qcontext.get('token') and not qcontext.get('signup_enabled'):
            raise werkzeug.exceptions.NotFound()
        if 'error' in qcontext:
            raise UserError(qcontext["error"])

        try:
            # 这个函数的作用是: 根据 token 或 用户名 查找或注册用户
            self.do_signup(qcontext)
            # 返回注册成功
            print('xxxxx,web_auth_signup2,True', qcontext)
            return True

        except UserError as e:
            raise UserError(e.args[0])

        except (SignupError, AssertionError) as e:
            if request.env["res.users"].sudo().search([("login", "=", qcontext.get("login"))]):
                raise UserError(_(
                    "Another user is already registered using this email address."))
            else:
                _logger.error("%s", e)
                raise UserError(_("Could not create a new account."))

    def get_auth_signup_qcontext(self):
        # from request.params
        # 'login', 'name', 'password' ,
        # confirm_password
        # lang
        # 1. qcontext = request.params.copy()
        # 2. signup_enabled
        # 3. reset_password_enabled
        # self.env['res.partner'].signup_retrieve_info(qcontext['token'])
        # 4. db / token / name / login / email
        # 5. error = 'Invalid signup token' /
        # 6. invalid_token

        qcontext = super().get_auth_signup_qcontext()
        return qcontext

    def do_signup(self, qcontext):
        # 获取 'login', 'name', 'password'
        # 比对两次密码是否一致.  这个在前端处理, 因此这里 是冗余的判断处理
        # 获取 lang, 安装需要的 lang
        # 获取 token, {'login', 'name', 'password',lang}, 注册
        # 注册时, 若无 token, 注册新用户
        # 若有 token, 查找不到 partner, 报错
        # 若有 token, 查找到 partner, 无用户创建, 有用户更新 'password',lang
        #
        res = super().do_signup(qcontext)
        return res
